package com.easymin.weixin.controller.res;

import com.easymin.weixin.common.DataGrid;
import com.easymin.weixin.entity.Intent;
import com.easymin.weixin.manager.PartnerManager;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("api/partner")
public class PartnerRes {
  
  private static final Logger logger = LoggerFactory.getLogger(PartnerRes.class);
  
  @Autowired
  private PartnerManager partnerManager;

  /**
   * 分页查询商家.
   */
  @RequestMapping(value = {"", "/"}, method = RequestMethod.GET)
  public @ResponseBody Map<String, Object> findPartners(
      @RequestParam("categoryAlias") String categoryAlias,
      @RequestParam(required = false, value = "intentId") Long intentId, 
      @RequestParam("longitude") Double longitude,
      @RequestParam("latitude") Double latitude,
      @RequestParam("page") Integer page,
      @RequestParam("rows") Integer rows, 
      @RequestParam("appKey") String appKey) throws Exception {
    Map<String, Object> map = new HashMap<String, Object>();

    appKey = StringUtils.trimToEmpty(appKey);


    DataGrid<Map<String, Object>> dataGrid =
        partnerManager
            .findByParam(categoryAlias, longitude, latitude, intentId, page, rows, appKey);

    try {
      map.put("code", 0);
      map.put("msg", "成功");
      map.put("data", dataGrid);
      return map;
    } catch (Exception ex) {
      logger.error(ex.getMessage());
      map.put("code", 500);
      map.put("msg", "加载数据失败");
      return map;
    }
  }

  /**
   * 根据主分类别名查询子分类.
   */
  @RequestMapping(value = "findIntent", method = RequestMethod.GET)
  public @ResponseBody Map<String, Object> findPartners(
      @RequestParam("categoryAlias") String categoryAlias, @RequestParam("appKey") String appKey)
      throws Exception {
    Map<String, Object> map = new HashMap<String, Object>();

    appKey = StringUtils.trimToEmpty(appKey);
    List<Intent> list = partnerManager.findIntents(categoryAlias, appKey);
    try {
      map.put("code", 0);
      map.put("msg", "成功");
      map.put("data", list);
      return map;
    } catch (Exception ex) {
      logger.error(ex.getMessage());
      map.put("code", 500);
      map.put("msg", "加载数据失败");
      return map;
    }
  }
}
